from fastapi import FastAPI, Request
import time


def logger_middleware(app: FastAPI):
    """
    日志处理中间件
    """

    @app.middleware("http")
    async def logger(request: Request, call_next):
        message = f"{request.client.host}:{request.client.port} {request.method} {request.url.path}"
        print(message)
        response = await call_next(request)
        return response


def process_time_middleware(app: FastAPI):
    """
    处理时间中间件
    """

    @app.middleware("http")
    async def add_process_time_header(request: Request, call_next):
        start_time = time.perf_counter()
        response = await call_next(request)
        process_time = time.perf_counter() - start_time
        print("process time: ", process_time)
        response.headers["X-Process-Time"] = str(process_time)
        return response
